package com.bitcat.firstapp.demo.newslistdemo

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivitySmartRefreshDemoBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

class SmartRefreshDemoActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivitySmartRefreshDemoBinding.inflate(layoutInflater)
    }

    private val adapter by lazy {
        RefreshAdapter(mutableListOf())
    }

    private var page = 1


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        binding.recyclerView.adapter = adapter

//        binding.refreshLayout.setOnRefreshListener {  }
//        binding.refreshLayout.setOnLoadMoreListener {  }

        //设置下拉刷新和上拉加载的监听
        binding.refreshLayout.setOnRefreshLoadMoreListener(object:OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                //下拉刷新
                page = 1
                loadData(true)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                //上拉加载
               page++
                loadData(false)
            }
        })

        binding.refreshLayout.autoRefresh()
    }

    fun loadData(isRefresh:Boolean){

        if (!isRefresh && page >3){
            binding.refreshLayout.finishLoadMoreWithNoMoreData()
            return
        }


        val newItems = generateData()

        if (isRefresh){
            adapter.refreshData(newItems)
            binding.refreshLayout.finishRefresh()
        }else{
            adapter.loadMore(newItems)
            binding.refreshLayout.finishLoadMore()
        }
    }



    fun generateData():List<RefreshDemoItem>{
        val itemCount = if (page  == 3) 2 else 10
        return List(itemCount){index->
            val itemIndex = (page -1) * 10 + index + 1   //1-10  11-20
            RefreshDemoItem(title = "title$itemIndex", content = "content$itemIndex")
        }
    }
}